package com.yt.app.api.action;

import com.google.common.base.Splitter;
import com.yt.app.api.action.base.BaseAction;
import com.yt.app.api.util.Config;
import com.yt.app.api.vo.BaseVo;
import com.yt.app.api.vo.UserOrderVo;
import com.yt.app.core.interfaces.UserOrderDetailService;
import com.yt.app.core.interfaces.UserOrderService;
import com.yt.app.core.model.UserOrder;
import com.yt.app.core.model.UserOrderDetail;
import com.yt.app.core.utils.Constant;
import com.yt.core.MsgBean;
import com.yt.order.api.interfaces.InstitutionService;
import com.yt.order.api.interfaces.OrderNumberService;
import com.yt.order.api.interfaces.ProductService;
import com.yt.order.api.model.Institution;
import com.yt.order.api.model.Product;
import com.yt.util.RandomUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;

@Controller
@Api(tags = "08.订单预约")
@RequestMapping("/order")
public class OrderController extends BaseAction{
    @Autowired
    private ProductService productService;
    @Autowired
    private InstitutionService institutionService;
    @Autowired
    private UserOrderService userOrderService;
    @Autowired
    private UserOrderDetailService userOrderDetailService;
    @Autowired
    private OrderNumberService orderNumberService;

    @ApiOperation(value="创建订单", httpMethod = "POST")
    @RequestMapping("/create")
    @ApiResponses(value = {@ApiResponse(code = 200,message = "订单信息", response = UserOrder.class)})
    public @ResponseBody  Object createOrder(
            @ApiParam("商品信息,格式：商品ID,商品数量;商品ID,商品数量;...") @RequestParam(value = "products", required = true, defaultValue = "0") String products,
            @ApiParam("订单类型, 0:非实物订单，1:实物订单") @RequestParam(value = "orderType", required = true, defaultValue = "0") String orderType,
            @ApiParam("收件人") @RequestParam(value="buyUser", required = false) String buyUser,
            @ApiParam("收件地址") @RequestParam(value="address", required = false) String address,
            @ApiParam("邮编") @RequestParam(value="postcode", required = false) String postcode,
            @ApiParam("手机号") @RequestParam(value="mobile", required = false) String mobile,
            @ApiParam("备注") @RequestParam(value="comment", required = false) String comment,
            @ApiIgnore HttpServletRequest request
    ){
        MsgBean msgBean = new MsgBean();
        Long uid = BaseVo.getUIDFromHeader(request);
        Map<String, String> productMap = Splitter.on(";").withKeyValueSeparator(",").split(products);
        Set<Map.Entry<String, String>> productEntry = productMap.entrySet();
        Long totalAmount = 0L;
        List<UserOrderDetail> userOrderDetailList = new ArrayList<UserOrderDetail>();
        for(Map.Entry<String, String> p : productEntry){
            if(!NumberUtils.isNumber(p.getKey()) || !NumberUtils.isNumber(p.getValue())){
                return msgBean.failure("商品ID或数量有误！").returnMsg();
            }
            Long pId = Long.parseLong(p.getKey());
            Integer pCount = Integer.parseInt(p.getValue());
            Product product = productService.get(pId);
            Institution institution = institutionService.get(product.getIdInstitution());
            if(product == null){
                return msgBean.failure("商品不存在！").returnMsg();
            }else if("0".equals(product.getIsPublic()) || "0".equals(product.getOnsale())){
                return msgBean.failure("商品已下架！").returnMsg();
            }
            for(int i=0; i< pCount; i++) {
                UserOrderDetail orderDetail = new UserOrderDetail();
                orderDetail.setUid(uid);
                orderDetail.setSalePrice(product.getSalePrice());
                orderDetail.setBasePrice(product.getBasePrice());
                orderDetail.setAmount(product.getSalePrice());
                orderDetail.setProductId(product.getId());
                orderDetail.setProductName(product.getName());
                orderDetail.setImageFile(product.getImageFile() == null?"":product.getImageFile());
                orderDetail.setInstitutionId(product.getIdInstitution());
                orderDetail.setInstitutionName(institution.getName());
                orderDetail.setProductCount(1);
                orderDetail.setLeftCount(1);
                userOrderDetailList.add(orderDetail);
                //累计
                totalAmount += orderDetail.getAmount();
            }
        }
        UserOrder userOrder = new UserOrder();
        userOrder.setBuyUser(buyUser);
        if(Constant.ORDER_TYPE.Object.value().equals(orderType)) {
            userOrder.setAddress(address);
            userOrder.setPostcode(postcode);
        }else{
            userOrder.setAddress("");
            userOrder.setPostcode("");
        }
        userOrder.setOrderType(orderType);
        userOrder.setUid(uid);
        userOrder.setMobile(mobile);
        userOrder.setOrderTime(System.currentTimeMillis()/1000);
        userOrder.setModifyDate(System.currentTimeMillis()/1000);
        userOrder.setOrderStatus(Constant.ORDER_STATUS.NOT_PAY.value());
        userOrder.setComment(comment);
        userOrder.setAmount(totalAmount);
        userOrder.setPayType(String.valueOf(Constant.PAY_TYPE.NOT_SET.value()));
        String orderNumber = orderNumberService.nextAppOrderNumber(new Date());
        userOrder.setOrderNo(orderNumber);

        userOrderService.insert(userOrder);

        userOrder = userOrderService.getByOrderNo(orderNumber);
        if(userOrder == null){
            return msgBean.failure("订单保存失败，请重试!").returnMsg();
        }
        Long orderId = userOrder.getId();
        //补充UserOrderDetail中的订单ID,并保存
        int idx = 1;
        for(UserOrderDetail detail : userOrderDetailList){
            detail.setUserOrderId(orderId);
            detail.setCardNo(orderNumber + String.format("%03d",idx));
            detail.setCardPassword(Config.env.equals("product")?RandomUtil.getRandomNumCode(6):"999999");
            userOrderDetailService.insert(detail);
            idx ++;
        }
        msgBean.put("order", userOrder);
        return msgBean.returnMsg();
    }

}
